package com.juyu.miliao.api.dao.elasticsearch;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.FindCommentReplyInfo;
import com.juyu.miliao.api.domain.FindDynamicCommentInfo;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.domain.dto.FindCommentReplyElasticsearchDTO;
import com.juyu.miliao.api.domain.vo.FindCommentReplyVO;
import com.juyu.miliao.api.domain.vo.FindDynamicCommentVO;
import com.juyu.miliao.api.util.PageUtil;
import com.juyu.miliao.common.util.DateUtil;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xuanqicheng
 */
@Repository
public class FindCommentReplyElasticsearch {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserInfoCache userInfoCache;


    public void addFindDynamicCommentInfo(FindCommentReplyInfo findCommentReplyInfo) throws IOException {
        IndexRequest request = new IndexRequest("find_comment_reply_info", "findCommentReplyInfo",
                findCommentReplyInfo.getId() + "");

        request.source(objectMapper.writeValueAsString(findCommentReplyInfo), XContentType.JSON);

        restHighLevelClient.index(request, RequestOptions.DEFAULT);
    }

    public long getCount(long commentId) throws IOException {
        SearchRequest searchRequest = new SearchRequest("find_comment_reply_info");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder = new TermQueryBuilder("commentId", commentId);

        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.size(0);
        searchRequest.source(searchSourceBuilder);

        SearchResponse res = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        return res.getHits().getTotalHits();

    }

    public List<FindCommentReplyVO> selectPage(long commentId,Integer page, Integer pageSize) throws IOException {
        int startNum = PageUtil.getOffset(page, pageSize);
        SearchRequest searchRequest = new SearchRequest("find_comment_reply_info");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.termQuery("commentId",commentId));
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));
        searchSourceBuilder.from(startNum);
        searchSourceBuilder.size(pageSize);


        searchSourceBuilder.sort(new FieldSortBuilder("replyTime").order(SortOrder.DESC));

        searchRequest.source(searchSourceBuilder);

        SearchResponse res = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);

        SearchHit[] hits = res.getHits().getHits();

        List<FindCommentReplyElasticsearchDTO> findCommentReplyElasticsearchDTOS = new ArrayList<>();
        for(SearchHit hit : hits){

            FindCommentReplyElasticsearchDTO findDynamicCommentVO =objectMapper.readValue(hit.getSourceAsString(),
                    FindCommentReplyElasticsearchDTO.class);

            findCommentReplyElasticsearchDTOS.add(findDynamicCommentVO);
        }
        List<FindCommentReplyVO> list = new ArrayList<>();
        for(FindCommentReplyElasticsearchDTO obj : findCommentReplyElasticsearchDTOS){
            FindCommentReplyVO findCommentReplyVO = new FindCommentReplyVO();
            setFindCommentReplyVO(obj, findCommentReplyVO);

            list.add(findCommentReplyVO);
        }
        return list;
    }

    private void setFindCommentReplyVO(FindCommentReplyElasticsearchDTO obj, FindCommentReplyVO findCommentReplyVO) {
        BeanUtils.copyProperties(obj,findCommentReplyVO);
        UserCacheVo replyFromUser=userInfoCache.getUserCacheInfo(obj.getReplyFromUserId());
        findCommentReplyVO.setReplyFromIsHost(replyFromUser.getIsHost());
        findCommentReplyVO.setReplyFromUserNickName(replyFromUser.getNickName());
        findCommentReplyVO.setReplyFromUserIcon(replyFromUser.getIcon());
        findCommentReplyVO.setReplyFromEnergyGrade(replyFromUser.getUserLevel()
                .getEnergyGrade());
        String replyFromLevelPic = replyFromUser.getUserLevel().getLevelPic();

        findCommentReplyVO.setReplyFromLevelPic(replyFromLevelPic==null?"":replyFromLevelPic);

        Integer replyFromHostUserGrade = replyFromUser.getHostUserLevel().getHostUserGrade();
        findCommentReplyVO.setReplyFromHostUserGrade(replyFromHostUserGrade==null
                ?0:replyFromHostUserGrade);
        String replyFromHostPic = replyFromUser.getHostUserLevel().getHostUserGradePic();
        findCommentReplyVO.setReplyFromHostUserGradePic(replyFromHostPic==null
                ? "":replyFromHostPic);

        UserCacheVo replyToUser = userInfoCache.getUserCacheInfo(findCommentReplyVO.getReplyToUserId());
        if(findCommentReplyVO.getReplyToUserId()==1){
            findCommentReplyVO.setReplyToUserNickName(replyToUser.getNickName());
        }else{
            findCommentReplyVO.setReplyToUserNickName("@ "+replyToUser.getNickName());
        }
        findCommentReplyVO.setReplyToIsHost(replyToUser.getIsHost());
        findCommentReplyVO.setReplyToUserIcon(replyToUser.getIcon());

        findCommentReplyVO.setReplyToEnergyGrade(replyToUser.getUserLevel()
                .getEnergyGrade());
        String replyToLevelPic = replyToUser.getUserLevel().getLevelPic();

        findCommentReplyVO.setReplyToLevelPic(replyToLevelPic==null?"":replyToLevelPic);
        Integer replyToHostGrade = replyToUser.getHostUserLevel().getHostUserGrade();
        findCommentReplyVO.setReplyToHostUserGrade(replyToHostGrade==null
                ? 0:replyToHostGrade);
        String replyToHostPic = replyToUser.getHostUserLevel().getHostUserGradePic();
        findCommentReplyVO.setReplyToHostUserGradePic(replyToHostPic==null ? "":replyToHostPic);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        String showTime = DateUtil.getShowTime(LocalDateTime.parse(obj.getReplyTime(), df));

        findCommentReplyVO.setShowTime(showTime);
    }

    /**
     * 根据id 获取回复信息
     * @param id 回复id
     * @return
     */
    public FindCommentReplyVO getFindCommentReplyVOById(long id) throws IOException {
        SearchRequest searchRequest = new SearchRequest("find_comment_reply_info");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.termQuery("id",id));
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));

        searchRequest.source(searchSourceBuilder);

        SearchResponse res = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);

        SearchHit[] hits = res.getHits().getHits();

        FindCommentReplyElasticsearchDTO obj = null;

        if (hits.length>0) {

            obj = objectMapper.readValue(hits[0].getSourceAsString(),
                    FindCommentReplyElasticsearchDTO.class);
        }

        FindCommentReplyVO findCommentReplyVO = new FindCommentReplyVO();

        if(obj!=null){
            setFindCommentReplyVO(obj,findCommentReplyVO);
//            BeanUtils.copyProperties(obj,findCommentReplyVO);
//            UserCacheVo replyFromUser=userInfoCache.getUserCacheInfo(obj.getReplyFromUserId());
//            findCommentReplyVO.setReplyFromUserNickName(replyFromUser.getNickName());
//            findCommentReplyVO.setReplyFromUserIcon(replyFromUser.getIcon());
//            UserCacheVo replyToUser = userInfoCache.getUserCacheInfo(findCommentReplyVO.getReplyToUserId());
//            if(findCommentReplyVO.getReplyToUserId()==1){
//                findCommentReplyVO.setReplyToUserNickName(replyToUser.getNickName());
//            }else{
//                findCommentReplyVO.setReplyToUserNickName("@ "+replyToUser.getNickName());
//            }
//            findCommentReplyVO.setReplyToUserIcon(replyToUser.getIcon());
//
//            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//
//            String showTime = DateUtil.getShowTime(LocalDateTime.parse(obj.getReplyTime(), df));
//
//            findCommentReplyVO.setShowTime(showTime);

        }

        return findCommentReplyVO;

    }
}
